package de.openkanban.server.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang.StringUtils;

import de.openkanban.server.domain.User;

public class MultipartUtil {

	public static User processFiles(HttpServletRequest request, HttpServletResponse response) {
		SecureRandom random = new SecureRandom();
		String generatedFileName = new BigInteger(80, random).toString(32);
		return processFiles(generatedFileName, request, response);
	}

	@SuppressWarnings("unused")
	public static User processFiles(String targetFileName, HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, String> args = new HashMap<String, String>();
		boolean isGWT = true;
		try {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(request);
			// pick up parameters first and note actual FileItem
			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				String name = item.getFieldName();
				if (item.isFormField()) {
					args.put(name, Streams.asString(item.openStream()));
				} else {
					args.put("contentType", item.getContentType());
					String fileName = item.getName();
					if (StringUtils.isNotBlank(fileName)) {

						int slash = fileName.lastIndexOf("/");
						if (slash < 0)
							slash = fileName.lastIndexOf("\\");
						if (slash > 0)
							fileName = fileName.substring(slash + 1);

						String[] fileNameArr = fileName.split("\\.");

						targetFileName += "." + fileNameArr[fileNameArr.length - 1];

						args.put("fileName", targetFileName);

						String contextName = args.get("context");
						String model = args.get("model");
						String path = args.get("path");
						if (contextName == null) {
							isGWT = false;
							contextName = request.getParameter("context");
							model = request.getParameter("model");
							path = request.getParameter("path");
						}
						InputStream in = null;
						try {
							in = item.openStream();

							File f = new File(request.getSession().getServletContext().getRealPath("")
									+ "/images/avatar/" + args.get("fileName"));

							OutputStream out = new FileOutputStream(f);
							byte buf[] = new byte[1024];
							int len;
							while ((len = in.read(buf)) > 0)
								out.write(buf, 0, len);
							out.close();

						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							if (in != null)
								try {
								} catch (Exception e) {
								}
						}
					}
				}
			}

			User user = new User();

			user.setVorname(args.get("vorname"));
			user.setNachname(args.get("nachname"));
			user.setEmail(args.get("email"));
			user.setPassword(args.get("password"));
			user.setNamensKuerzel(args.get("namensKuerzel"));

			if (args.containsKey("fileName")) {
				user.setAvatarUrl(args.get("fileName"));
			}

			return user;

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return null;
	}
}
